import { Request, Response } from 'express'
import { albumsService } from '@/services/albums'
import { uploadMemorySingle } from '@/utils/upload'
import { hasS3, uploadBufferToS3 } from '@/utils/s3'
import { logger } from '@/utils/logger'

export class AlbumsController {
  private async getPartnerId(userId: string): Promise<string | null> {
    try {
      const user = await (await import('@/config/database')).prisma.user.findUnique({
        where: { id: userId },
        select: { partnerId: true },
      })
      return user?.partnerId || null
    } catch {
      return null
    }
  }

  listAlbums = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      if (!userId) return res.status(401).json({ success: false, message: '未认证' })
      const partnerId = await this.getPartnerId(userId)
      const albums = await albumsService.listAlbums(userId, partnerId)
      res.json({ success: true, data: albums })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '获取相册失败' })
    }
  }

  createAlbum = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      const { title, coverUrl } = req.body
      if (!title) return res.status(400).json({ success: false, message: '标题必填' })
      const album = await albumsService.createAlbum(userId, title, coverUrl)
      res.json({ success: true, data: album })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '创建相册失败' })
    }
  }

  updateAlbum = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      const { id } = req.params
      const { title, coverUrl } = req.body
      const album = await albumsService.updateAlbum(userId, id, { title, coverUrl })
      res.json({ success: true, data: album })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '更新相册失败' })
    }
  }

  deleteAlbum = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      const { id } = req.params
      await albumsService.deleteAlbum(userId, id)
      res.json({ success: true })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '删除相册失败' })
    }
  }

  listPhotos = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      if (!userId) return res.status(401).json({ success: false, message: '未认证' })
      const partnerId = await this.getPartnerId(userId)
      const { albumId } = req.params
      const photos = await albumsService.listPhotos(userId, partnerId, albumId)
      res.json({ success: true, data: photos })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '获取照片失败' })
    }
  }

  uploadPhoto = [
    uploadMemorySingle('file'),
    async (req: any, res: Response) => {
      try {
        if (!hasS3()) {
          return res.status(500).json({ success: false, message: '对象存储未配置' })
        }
        const userId = req.user?.id || req.userId || req.user?.userId
        if (!userId) return res.status(401).json({ success: false, message: '未认证' })
        const partnerId = await this.getPartnerId(userId)
        const { albumId } = req.params
        const file = req.file
        if (!file) return res.status(400).json({ success: false, message: '未选择文件' })

        const ext = (file.originalname.split('.').pop() || '').toLowerCase()
        const key = `albums/${albumId}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext || 'bin'}`
        const url = await uploadBufferToS3(key, file.buffer, file.mimetype)

        const { title, description, width, height, tags } = req.body
        const photo = await albumsService.addPhoto(userId, partnerId, {
          albumId,
          url,
          mime: file.mimetype,
          size: file.size,
          title,
          description,
          width: width ? parseInt(width) : undefined,
          height: height ? parseInt(height) : undefined,
          tags: tags ? String(tags).split(',').map((t) => t.trim()).filter(Boolean) : [],
        })

        res.json({ success: true, data: photo })
      } catch (e: any) {
        logger.error('上传照片失败', e)
        res.status(400).json({ success: false, message: e.message || '上传照片失败' })
      }
    }
  ]

  deletePhoto = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      const { id } = req.params
      await albumsService.deletePhoto(userId, id)
      res.json({ success: true })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '删除照片失败' })
    }
  }

  toggleLike = async (req: any, res: Response) => {
    try {
      const userId = req.user?.id || req.userId || req.user?.userId
      const { id } = req.params
      const photo = await albumsService.toggleLike(userId, id)
      res.json({ success: true, data: photo })
    } catch (e: any) {
      res.status(400).json({ success: false, message: e.message || '点赞失败' })
    }
  }
}